package com.habdqn.studentmanager.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.github.xiaofan1519.verify.core.Verify;
import com.github.xiaofan1519.verify.exception.VerifyException;
import com.habdqn.studentmanager.bean.Dictionary;
import com.habdqn.studentmanager.bean.Product;
import com.habdqn.studentmanager.bean.ajax.ProductRes;
import com.habdqn.studentmanager.bean.ajax.Response;
import com.habdqn.studentmanager.constant.DictType;
import com.habdqn.studentmanager.constant.ErrorCode;
import com.habdqn.studentmanager.constant.FieldDefine;
import com.habdqn.studentmanager.exception.StudentException;
import com.habdqn.studentmanager.service.DictionaryService;
import com.habdqn.studentmanager.service.ProductService;

/**
 * 
 * @author Administrator
 * 
 *         2017年5月16日
 *
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    private Logger logger = Logger.getLogger(ProductController.class);

    @Resource
    private ProductService productService;

    @Resource
    private DictionaryService dictService;

    @RequestMapping("/list")
    public String getProductList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @ModelAttribute("bean") Product bean, Model model) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        List<Dictionary> types = dictService.findList(Dictionary.make(DictType.ProductType, null, null));
        model.addAttribute("types", types);

        PageInfo<Product> page = productService.findProductList(pageNum, pageSize, bean);
        model.addAttribute("pageInfo", page);
        return "product/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Response addProduct(@RequestBody Product bean) {
        Response response = new Response();
        if (StringUtils.isEmpty(bean.getName()) || StringUtils.isEmpty(bean.getType())) {
            logger.debug("产品名称或类型为空！");
            response = Response.make(ErrorCode.Invalid_Argument, "非法参数");
            return response;
        }

        try {
            productService.addProduct(bean);
            return response;
        }
        catch (StudentException e) {
            logger.error("添加产品失败", e);
            response = Response.make(ErrorCode.System_Error, e.getMessage());
            return response;
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Response delete(@RequestBody Product bean) {
        Response rsp = new Response();

        if (null == bean || null == bean.getId()) {
            logger.debug("product:" + bean);
            return Response.make(ErrorCode.Invalid_Argument, "参数非法");
        }

        try {
            productService.delete(bean);
        }
        catch (StudentException e) {
            logger.debug("删除失败", e);
            rsp = Response.make(ErrorCode.System_Error, e.getMessage());
        }
        catch (Exception e) {
            logger.error("系统异常", e);
            rsp = Response.make(ErrorCode.System_Error, "系统异常");
        }

        return rsp;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Response update(@RequestBody Product bean) {

        try {
            Verify.verifyNull(bean);
            Verify.verifyLen(bean.getName(), 1, FieldDefine.MAX_PASSWD_LENTH);
            Verify.verifyNull(bean.getType());
            Verify.verifyNull(bean.getType().getValue());
        }
        catch (VerifyException e) {
            logger.debug("校验失败", e);
            return Response.make(ErrorCode.Invalid_Argument, "参数非法");
        }

        try {
            productService.update(bean);
        }
        catch (StudentException e) {
            return Response.make(ErrorCode.System_Error, "更新产品失败");
        }

        return new Response();
    }

    /**
     * ajax请求，根据id获取产品
     * 
     * @return
     */
    @RequestMapping(value = "find", method = RequestMethod.POST)
    @ResponseBody
    public ProductRes find(@RequestBody Product product) {
        ProductRes res = new ProductRes();
        Product bean = null;
        try {
            Verify.verifyNull(product.getId());
            bean = productService.findById(product.getId());
            if (bean == null) {
                res = (ProductRes) ProductRes.make(ErrorCode.Notfound, "没有找到指定产品");
            }
            else {
                res.setProduct(bean);
            }
        }
        catch (VerifyException e) {
            logger.error("非法参数", e);
            res = (ProductRes) ProductRes.make(ErrorCode.Invalid_Argument, "非法参数");
        }
        catch (StudentException e) {
            logger.error("系统错误", e);
            res = (ProductRes) ProductRes.make(ErrorCode.System_Error, "系统错误");
        }
        return res;
    }
}
